package com.liz.lizrpccore.lizspring.postprocessor;

import com.liz.lizrpccore.annotations.CustomerResource;
import com.liz.lizrpccore.beans.ResourceBean;
import com.liz.lizrpccore.utils.LizStringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;

/**
 * @author liangGongWei
 * @description
 * @create 2022-04-13 17:41
 **/

public class CustomerResourceAnnotationBeanPostProcessor implements BeanPostProcessor {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    public static final String BEAN_NAME = "referenceAnnotationBeanPostProcessor";

    /**
    * 这个方法在 spring初始化 bean 调用 initializeBean 方法中被执行，
     * 我们在这里，将带有 CustomerResource 注解的属性，注入到 实例化好的 bean中  （实例化方法是  createBeanInstance ）
    */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> aClass = bean.getClass();

        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            if (!field.isAnnotationPresent(CustomerResource.class)) {
                continue;
            }
            String key = LizStringUtil.toLowerFirstLetterCase(field.getType().getName());

            field.setAccessible(true);
            try {
                ResourceBean lizRpcProxy = this.getLizRpcProxy(key);
                if (null == lizRpcProxy) {
                } else {
                    Object object = lizRpcProxy.getObject();
                    field.set(bean, object);
                }
            } catch (Throwable t) {
                logger.warn("注入失败-bean:{},field:{}", beanName, key);
            }
        }
        return bean;
    }

    private ResourceBean getLizRpcProxy(String className) {
        try {
            Class<?> interfaceType = Class.forName(className);
            return new ResourceBean<>(interfaceType);
        } catch (Throwable t) {
            logger.warn("create proxy Object failed，error:{}", t.getMessage());
            return null;
        }
    }
}
